package com.uenpay.im.ui.old.activity.contacts;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qiyunxin.android.http.cache.HttpStreamCache;
import com.qyx.android.database.DBFriendColumns;
import com.qyx.android.database.DBTopMsgColumns;
import com.qyx.android.database.FriendDB;
import com.qyx.android.database.TalkMsgManager;
import com.qyx.android.database.TopListMsgManager;
import com.qyx.android.entity.FriendEntity;
import com.qyx.android.message.type.PacketType;
import com.uenpay.im.BroadcastAction;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ActivityHandle;
import com.uenpay.im.ui.old.activity.remark.SetRemarkActivity;
import com.uenpay.im.ui.old.activity.transfer.TransferActivity;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.callback.OnCommonCallBack;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.entities.QYXUserEntity;
import com.uenpay.im.invokeitems.contacts.ApplyAddFriendInvokItem;
import com.uenpay.im.invokeitems.contacts.DeleteFriendsInvokItem;
import com.uenpay.im.view.PictureShowActivity;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.MyDialog;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.MessageFormat;
import java.util.ArrayList;

/**
 * 好友资料
 *
 * @author SL
 * @copyRight http://www.qiyunxin.com
 */
public class UserDetailActivity extends BaseActivity {

    private ImageView user_detail_sex_iv;
    private TextView user_detail_name, user_detail_nick_name,
            user_detail_remark_describe, user_detail_age, user_detail_email,
            user_detail_app_name, user_detail_area;
    private View loading;
    private RoundImageView user_detail_avatar;
    private Button send_msg_btn, apply_add_friends_btn, transfer_btn;
    private String to_cust_id = "";
    private TopListMsgManager topListMsgManager = new TopListMsgManager();
    /**
     * 会话消息管理
     */
    private TalkMsgManager msgManager = new TalkMsgManager();
    private String cust_id = "";
    private String userName = "";
    private LinearLayout bottom_layout, nick_name_layout,
            remark_describe_layout, phone_num_layout, remark_phone_num_layout;
    /**
     * 设置备注
     */
    private RelativeLayout set_notes_layout;
    private ScrollView scrollview;
    private QYXUserEntity qyxUserEntity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_user_detail_layout;
    }

    @Override
    public void initView(View view) {
        cust_id = getIntent().getStringExtra("cust_id");
        initView();
        initListener();
        getInfo(cust_id);
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview)).setText(getResources()
                .getString(R.string.me_detail));
        user_detail_name = (TextView) findViewById(R.id.user_detail_name);
        user_detail_nick_name = (TextView) findViewById(R.id.user_detail_nick_name);
        user_detail_remark_describe = (TextView) findViewById(R.id.user_detail_remark_describe);
        user_detail_area = (TextView) findViewById(R.id.user_detail_area);
        user_detail_age = (TextView) findViewById(R.id.user_detail_age);
        user_detail_email = (TextView) findViewById(R.id.user_detail_email);
        user_detail_app_name = (TextView) findViewById(R.id.user_detail_app_id);
        loading = findViewById(R.id.loading);
        send_msg_btn = (Button) findViewById(R.id.send_msg_btn);
        user_detail_sex_iv = (ImageView) findViewById(R.id.user_detail_sex_iv);
        apply_add_friends_btn = (Button) findViewById(R.id.apply_add_friends_btn);
        user_detail_avatar = (RoundImageView) findViewById(R.id.user_detail_avatar);
        bottom_layout = (LinearLayout) findViewById(R.id.bottom_layout);
        nick_name_layout = (LinearLayout) findViewById(R.id.nick_name_layout);
        remark_describe_layout = (LinearLayout) findViewById(R.id.remark_describe_layout);
        remark_phone_num_layout = (LinearLayout) findViewById(R.id.remark_phone_num_layout);
        phone_num_layout = (LinearLayout) findViewById(R.id.phone_num_layout);
        set_notes_layout = (RelativeLayout) findViewById(R.id.set_notes_layout);
        scrollview = (ScrollView) findViewById(R.id.scrollview);
        transfer_btn = (Button) findViewById(R.id.transfer_btn);
    }

    protected void initListener() {
        //返回键点击
        findViewById(R.id.back_layout).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish();
            }
        });

        findViewById(R.id.report_friend_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (!TextUtils.isEmpty(to_cust_id)) {
                            Bundle bundle = new Bundle();
                            bundle.putString("to_cust_id", to_cust_id);
                            ActivityHandle.startActivity(
                                    UserDetailActivity.this,
                                    ReportContactsOrGroupActivity.class,
                                    bundle, -1);
                        }
                    }
                });
        set_notes_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Bundle bundle = new Bundle();
                bundle.putString("to_cust_id", to_cust_id);
                bundle.putString("userName", userName);
                ActivityHandle.startActivity(
                        UserDetailActivity.this,
                        SetRemarkActivity.class,
                        bundle, 100);
            }
        });

        remark_describe_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Bundle bundle = new Bundle();
                bundle.putString("to_cust_id", to_cust_id);
                bundle.putBoolean("is_update", true);
                ActivityHandle.startActivity(
                        UserDetailActivity.this,
                        SetRemarkActivity.class,
                        bundle, 100);
            }
        });
        remark_phone_num_layout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Bundle bundle = new Bundle();
                bundle.putString("to_cust_id", to_cust_id);
                bundle.putBoolean("is_update", true);
                ActivityHandle.startActivity(
                        UserDetailActivity.this,
                        SetRemarkActivity.class,
                        bundle, 100);
            }
        });

        findViewById(R.id.delete_friend_layout).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (!TextUtils.isEmpty(to_cust_id)) {
                            deleteFriendsDailog();
                        }
                    }
                });
        user_detail_avatar.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String big_path = APIConfiguration.getAvatarUrlBig(cust_id,
                        PacketType.PERSONAL);
                ArrayList<String> imgs = new ArrayList<String>();
                Intent show = new Intent(UserDetailActivity.this,
                        PictureShowActivity.class);
                show.putExtra("content", big_path);
                imgs.add(big_path);
                show.putStringArrayListExtra("imgList", imgs);
                startActivity(show);
            }
        });

        findViewById(R.id.send_msg_btn).setOnClickListener(
                new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        if (TextUtils.isEmpty(to_cust_id)) {
                            return;
                        }
                        ActivityHandle.startChat(UserDetailActivity.this,
                                Long.valueOf(to_cust_id), PacketType.PERSONAL,
                                0, userName, 0, null);
                        finish();
                    }
                });
        apply_add_friends_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                applyAddFriend();
            }
        });
        transfer_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO 转账
                if (qyxUserEntity != null) {
                    Intent mIntent = new Intent(UserDetailActivity.this,
                            TransferActivity.class);
                    mIntent.putExtra("cust_id", cust_id);
                    mIntent.putExtra("cust_name", qyxUserEntity.nickname);
                    mIntent.putExtra("cust_account", qyxUserEntity.mobile);
                    startActivity(mIntent);
                }
            }
        });
    }

    private void getInfo(String cust_id) {
        loading.setVisibility(View.VISIBLE);

        ContactsHandle.getUserDetail(cust_id, new ContactsHandle.IGetUserDetailListener() {

            @Override
            public void onGetUserDetailResult(int status, String msg,
                                              QYXUserEntity user, boolean isCache) {
                qyxUserEntity = user;
                myHandler.sendEmptyMessage(0);
                if (status == HttpInvokeResultCode.RESULT_OK && user != null) {
                    initUserData(user, isCache);
                } else if (!TextUtils.isEmpty(msg)) {
                    IMApplication.showToast(msg);
                }
            }
        });

    }

    /**
     * 申请加好友
     */
    private void applyAddFriend() {
        loading.setVisibility(View.VISIBLE);

        ContactsHandle.applyAddFriend(to_cust_id, "", new OnCommonCallBack() {

            @Override
            public void onSuccess(Object result) {
                myHandler.sendEmptyMessage(0);
                ApplyAddFriendInvokItem.ApplyAddFriendInvokItemResult results = (ApplyAddFriendInvokItem.ApplyAddFriendInvokItemResult) result;
                IMApplication.showToast(results.msg);
                if (results != null
                        && results.status == HttpInvokeResultCode.RESULT_OK) {
                }

            }

            @Override
            public void onFailed(String reason) {
                myHandler.sendEmptyMessage(0);
                IMApplication.showToast(reason);
            }
        });

    }

    private void deleteFriends() {
        loading.setVisibility(View.VISIBLE);
        ContactsHandle.deleteFriends(to_cust_id, new OnCommonCallBack() {

            @Override
            public void onSuccess(Object result) {
                myHandler.sendEmptyMessage(0);
                DeleteFriendsInvokItem.DeleteFriendsInvokItemResult results = (DeleteFriendsInvokItem.DeleteFriendsInvokItemResult) result;
                if (result != null
                        && results.status == HttpInvokeResultCode.RESULT_OK) {
                    IMApplication.showToast(results.msg);
                    /**
                     * 数据删除该好友
                     */
                    FriendDB.deleteFriend(to_cust_id);
                    topListMsgManager.deleteByMsg(Long.valueOf(to_cust_id),
                            PacketType.PERSONAL);
                    msgManager.deleteMsgByFromCustIdAndToCustId(Long.valueOf(to_cust_id),
                            Long.valueOf(IMApplication.getCustId()));

                    Intent intent = new Intent(
                            BroadcastAction.DELETE_FRIEND_ACTION);
                    intent.putExtra("cust_id", to_cust_id);
                    sendBroadcast(intent);
                    finish();
                }
            }

            @Override
            public void onFailed(String reason) {
                IMApplication.showToast(reason);
                myHandler.sendEmptyMessage(0);
            }
        });
    }

    private void deleteFriendsDailog() {
        DialogUtility.showDialog(UserDetailActivity.this, MessageFormat.format(
                getResources().getString(R.string.delete_friend), userName),
                R.string.yes, R.string.no, true, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        deleteFriends();
                    }
                });

    }

    private void updateFriendInfo(QYXUserEntity qyxUserEntity) {
        FriendEntity friendEntity = FriendDB.getFriend(qyxUserEntity.custid);
        if (friendEntity == null
                || (qyxUserEntity.nickname.equals(friendEntity.nick_name) && qyxUserEntity.remarkname
                .equals(friendEntity.remarks_name))) {
            return;
        } else {
            boolean is_send = false;
            if (FriendDB.updateFriend(qyxUserEntity.custid,
                    DBFriendColumns.PINGYING_NAME, qyxUserEntity.pinyinname)) {
                is_send = true;
            }
            if (FriendDB.updateFriend(qyxUserEntity.custid,
                    DBFriendColumns.NICK_NAME, qyxUserEntity.nickname)) {
                is_send = true;
            }

            if (!TextUtils.isEmpty(qyxUserEntity.remarkname)) {
                if (topListMsgManager.updateTopMsgByField(
                        Long.valueOf(qyxUserEntity.custid),
                        PacketType.PERSONAL, DBTopMsgColumns.CHAT_NAME,
                        qyxUserEntity.remarkname) > 0) {
                    is_send = true;
                }
            } else {
                if (topListMsgManager.updateTopMsgByField(
                        Long.valueOf(qyxUserEntity.custid),
                        PacketType.PERSONAL, DBTopMsgColumns.CHAT_NAME,
                        qyxUserEntity.nickname) > 0) {
                    is_send = true;
                }
            }

            if (is_send) {
                Intent intent = new Intent(
                        BroadcastAction.ACTION_REFRESH_FRIEND_NAME);
                sendBroadcast(intent);
            }
        }
    }

    private Handler myHandler = new Handler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message arg0) {
            if (arg0.what == 0) {
                if (scrollview != null
                        && scrollview.getVisibility() == View.GONE) {
                    scrollview.setVisibility(View.VISIBLE);
                }
                if (loading != null) {
                    loading.setVisibility(View.GONE);
                }
            }
            return false;
        }
    });

    private View getPhoneNumView(String phoneNums, boolean is_show_view) {
        View view = View.inflate(UserDetailActivity.this,
                R.layout.item_remark_phone_layout, null);
        final TextView phoneNumTv = (TextView) view
                .findViewById(R.id.phone_num_tv);
        View line_view = view.findViewById(R.id.line_view);
        if (is_show_view) {
            line_view.setVisibility(View.VISIBLE);
        } else {
            line_view.setVisibility(View.GONE);
        }
        phoneNumTv.setText(phoneNums);
        phoneNumTv.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                String Telphone = phoneNumTv.getText().toString();
                deleteDialog(Telphone);
            }
        });
        return view;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {
            getInfo(cust_id);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void deleteDialog(final String phoneNum) {
        String[] call_phone_text = {IMApplication.getAppContext()
                .getResources().getString(R.string.call_phone)};

        final MyDialog.Builder dlg = new MyDialog.Builder(
                UserDetailActivity.this);
        final ListView menus = new ListView(UserDetailActivity.this);
        LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT);
        menus.setLayoutParams(params);
        menus.setTag(call_phone_text);
        menus.setAdapter(new ArrayAdapter<String>(IMApplication
                .getAppContext(), R.layout.custom_contenxt_menu_item,
                call_phone_text));

        dlg.setListView(menus);
        dlg.setMessage("");
        dlg.create().show();

        menus.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                switch (position) {
                    case 0:
                        Uri uri = Uri.parse("tel:" + phoneNum);
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        intent.setAction(Intent.ACTION_CALL);
                        intent.setData(uri);
                        startActivity(intent);
                        break;

                    default:
                        break;
                }
                dlg.getDialog().dismiss();
            }

        });

    }

    /**
     * 将备注保存在本地
     *
     * @param remarkName
     * @param phoneNum
     * @param memo
     */
    private void setRemarkInfoToLoca(String remarkName, String phoneNum,
                                     String memo) {
        JSONObject json = new JSONObject();
        try {
            json.put("remark_name", remarkName);
            json.put("phone_num", phoneNum);
            json.put("memo", memo);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if (json != null) {
            IMApplication.config.setStrangerFriendsJson(cust_id,
                    json.toString());
        }

        IMApplication.config.setFriendsRemarkName(cust_id, remarkName);
    }

    /**
     * 获取本地备注
     *
     * @param qyxUserEntity
     * @return
     */
    private QYXUserEntity getRemarkInfoByLoca(QYXUserEntity qyxUserEntity) {
        String content = IMApplication.config.getStrangerFriendsJson(cust_id);
        if (!TextUtils.isEmpty(content)) {
            try {
                JSONObject json = new JSONObject(content);
                if (json != null) {
                    if (json.has("remark_name")) {
                        qyxUserEntity.remarkname = json
                                .optString("remark_name");
                    }
                    if (json.has("phone_num")) {
                        qyxUserEntity.remarkPhonenumber = json
                                .optString("phone_num");
                    }
                    if (json.has("memo")) {
                        qyxUserEntity.remarkMemo = json.optString("memo");
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
                return qyxUserEntity;
            }
        }
        return qyxUserEntity;
    }

    /**
     * 显示数据
     *
     * @param user
     * @param isCache
     */
    private void initUserData(QYXUserEntity user, boolean isCache) {
        if (user.is_friend == 1) {
            /**
             * 将备注信息保存在本地
             */
            setRemarkInfoToLoca(user.remarkname, user.remarkPhonenumber,
                    user.remarkMemo);
        }
        user = getRemarkInfoByLoca(user);
        String small = APIConfiguration.getAvatarUrlNormal(user.custid,
                PacketType.PERSONAL);
        if (!isCache) {
            updateFriendInfo(user);

            String big = APIConfiguration.getAvatarUrlBig(user.custid,
                    PacketType.PERSONAL);
            HttpStreamCache.getInstance().ClearCacheBitmap(small);
            HttpStreamCache.getInstance().ClearCacheBitmap(big);
        }

        user_detail_avatar.SetUrl(small);
        if (!TextUtils.isEmpty(user.remarkname)) {
            userName = user.remarkname;
            user_detail_name.setText(user.nickname);
            user_detail_nick_name.setText(user.remarkname);
            nick_name_layout.setVisibility(View.VISIBLE);
        } else {
            userName = user.nickname;
            user_detail_name.setText(user.nickname);
            nick_name_layout.setVisibility(View.GONE);
        }

        /**
         * 备注
         */
        user_detail_remark_describe.setText(user.remarkMemo);
        if (!TextUtils.isEmpty(user.remarkMemo)) {
            remark_describe_layout.setVisibility(View.VISIBLE);
        } else {
            remark_describe_layout.setVisibility(View.GONE);
        }

        /**
         * 电话号码
         */
        if (!TextUtils.isEmpty(user.remarkPhonenumber)) {
            remark_phone_num_layout.setVisibility(View.VISIBLE);
        } else {
            remark_phone_num_layout.setVisibility(View.GONE);
        }

        phone_num_layout.removeAllViews();
        if (!TextUtils.isEmpty(user.remarkPhonenumber)) {
            if (user.remarkPhonenumber.indexOf(",") > -1) {
                String[] phoneNums = user.remarkPhonenumber.split(",");
                for (int i = 0, size = phoneNums.length; i < size; i++) {

                    phone_num_layout.addView(getPhoneNumView(phoneNums[i],
                            i == size - 1 ? false : true));
                }
            } else {
                phone_num_layout.addView(getPhoneNumView(
                        user.remarkPhonenumber, false));
            }
        }

        /**
         *
         */
        if (!TextUtils.isEmpty(user.remarkMemo)
                || !TextUtils.isEmpty(user.remarkPhonenumber)) {
            set_notes_layout.setVisibility(View.GONE);
            findViewById(R.id.remark_layout).setVisibility(View.VISIBLE);
        } else {
            set_notes_layout.setVisibility(View.VISIBLE);
            findViewById(R.id.remark_layout).setVisibility(View.GONE);
        }

        UserDetailActivity.this.to_cust_id = user.custid;
        user_detail_area.setText(user.area);
        if (user.sex == 1) {
            user_detail_sex_iv.setImageResource(R.drawable.icon_man);
        } else {
            user_detail_sex_iv.setImageResource(R.drawable.icon_woman);
        }
        user_detail_age.setText(user.age + "");
        user_detail_email.setText(user.email);
        user_detail_app_name.setText(user.idenum);
        /**
         * 用户关系1：好友
         */
        if (user.is_friend == 0) {
            apply_add_friends_btn.setVisibility(View.VISIBLE);
            send_msg_btn.setVisibility(View.GONE);
            bottom_layout.setVisibility(View.GONE);
        } else {
            apply_add_friends_btn.setVisibility(View.GONE);
            send_msg_btn.setVisibility(View.VISIBLE);
            bottom_layout.setVisibility(View.VISIBLE);
        }

    }
}
